using Core;
using UnityEngine;

namespace g_gongjianta
{
    public class BowMainComponent : UnitComponent<Bow>
    {
        public override void Awake()
        {
            base.Awake();

            ScreenEvent.OnChanged += OnScreenChangedHandler;
            // ScreenEvent.OnBtnControlClick += OnBtnControlClickHandler;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            ScreenEvent.OnChanged -= OnScreenChangedHandler;
            // ScreenEvent.OnBtnControlClick -= OnBtnControlClickHandler;

            base.Dispose();
        }

        private void OnScreenChangedHandler(Vector3 worldPosition)
        {
            var pos = new Vector2(worldPosition.x, worldPosition.y);

            // 计算从当前对象到目标点的向量
            var direction = pos - Unit.Pos;
            // 计算角度
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
            angle = Mathf.Clamp(angle, -45, 85);

            // 创建一个只绕 Z 轴旋转的 Quaternion
            var rotation = Quaternion.Euler(0, 0, angle);
            // 应用旋转
            Unit.transform.rotation = rotation;
        }

        // private void OnBtnControlClickHandler(string code)
        // {
        //     if (code != "all" && code != Unit.BtnCode)
        //     {
        //         return;
        //     }
        //
        //     log.err($"{Unit.gameObject.name}: 发射一只箭");
        // }
    }
}